require "TSLib"
require("tsp")
local scrTool = require("scr")
-------
function getscr()
	local scr
-- 	local path=appDataPath(frontAppBid()) or ''
	local path=appDataPath( app.bid ) or ''
	log(string.sub(path,#path) )
    if string.sub(path,#path) == '/' then 
    else
        log("增加/")
        path = path..'/' 
    end
    path = path.."Documents/recursiveDescription.txt"
    
    log(path)
    scrTool.print( app.bid  ) 
    -- scrTool.print( frontAppBid() ) 
    
    mSleep(200)
    for i=1,10 do if readFileString(path) and readFileString(path)~='' then mSleep(10) scr=readFileString(path) delFile(path) break else mSleep(100) end end
    if scr then return scr else toast('获取界面信息失败') mSleep(1000) return end
end
function scr2xy(str,scr)
	if not str then return end
    scr=scr or getscr() or ''
    if getScreenSize()==750 then sfbl_=2.0 else sfbl_=3.0 end --3.0为6p兼容参数
    local hidden = false
    local num_,line,num,str_
    local tmp={x=0,y=0,xy={}}
    local n=str:split('@')[2] or 1--n为第几个匹配坐标
    str=str:split('@')[1]
    line=scr:split(str)
    if not line[n+1] then return end
	str_=line[n+0]:split("text")
	str=str_[#str_]:gsub(" = '",''):gsub(": ",'')..str..line[n+1]:split(" frame")[1]:split("'")[1]
	if #str_>3 then
		str_={
		str_[#str_-3]:gsub(" = '",''):gsub(": ",''):split(" frame")[1]:split("'")[1],
		str_[#str_-2]:gsub(" = '",''):gsub(": ",''):split(" frame")[1]:split("'")[1],
		str_[#str_-1]:gsub(" = '",''):gsub(": ",''):split(" frame")[1]:split("'")[1],
		}--str的上一个文本
	else
		str_={}
	end
	if line[n+1]:split("text")[2] then
		for i=2,6 do
			if line[n+1]:split("text")[i] then
				str_[#str_+1]=line[n+1]:split("text")[i]:gsub(" = '",''):gsub(": ",''):split(" frame")[1]:split("'")[1]--i==2，str的下一个文本
			else
				break
			end
		end
	end
    scr=scr:split(line[n+1])[1]:split('\n')
    for i=#scr,1 ,-1 do
        line, num = scr[i]:gsub('   | ', '')
        num_=num_ or (num+1)
        if num<num_ and (num~=0 or i==1) and line:split('frame = (')[2] then
            num_=num
            tmp.xy=line:split('frame = (')[2]:split(';')[1]:split(' ')
            tmp.x=tmp.x+tmp.xy[1]
            tmp.y=tmp.y+tmp.xy[2]
            if line:find('hidden = YES') then hidden=true end
            if line:split('contentOffset: {')[2] then 
                tmp.xy=line:split('contentOffset: {')[2]:split('}')[1]:split(', ')
                tmp.x=tmp.x-tmp.xy[1]
                tmp.y=tmp.y-tmp.xy[2]
            end
        end
    end
    if tmp.x~=0 then return str,tmp.x*sfbl_,tmp.y*sfbl_,str_,hidden end
end
------

---[==[



thread = require('thread')
sz = require("sz") json = sz.json http = sz.i82.http

thread.create(function() while 1 do  resetIDLETimer() mSleep(29000) end end)--防止息屏
function beforeUserExit() closeFw() p('beforeUserExit-脚本结束') end
local w,h = getScreenSize()
-----------日志和toast
fwShowWnd("toast",0,0,w,h*0.03,0)
log('fwShowWnd-创建成功')
function p(str,t)
	if not initLog_ then initLog(_name or '', 0) initLog_=true end
    if str==true then str='true' end
    if str==false then str='false' end
    if type(str)=='table' then str=json.encode(str) end
    str=((str or 'nil')..''):gsub('\n',' '):gsub('\r',' ')
    thread.stop(threadid or '')
    threadid=thread.create(function()
        fwShowTextView('toast','提示',str,"center","000000","FFFFFF",0,0,0,0,w,h*0.03,1)
        mSleep((t or 2)*1000)
        fwCloseView('toast','提示');
    end)
    mSleep(1)
    local str_=os.date('[%m-%d-%H-%M-%S] ',os.time())..str
    wLog(_name,str_);
    nLog(str_)
end
function p_(...)
	if not initLog_ then initLog(_name or '', 0) initLog_=true end
    local _time=os.date('[%m-%d-%H-%M-%S] ',os.time())
    for k,v in ipairs{...} do
        if type(v)=='table' then v=json.encode(v) end
        _time=_time..v..','
    end
    nLog(_time:sub(1,#_time-1))
end
--------
UI={}
function UI.新建(抬头,配置)
    UINew(抬头,"运行脚本","退出脚本",配置..".dat",0,120,w,h,"255,255,255","255,255,255")
end
function UI.标题(文本,页数 )
    页数=页数 or 1
    UILabel(页数,文本,16,'center','200,20,20')
end
function UI.注释( 文本,页数 )
    页数=页数 or 1
    UILabel(页数,文本,14,'left','180,180,180')
end
function UI.输入框(变量名,默认值,宽度,页数)
    页数=页数 or 1
    宽度=宽度 or w*0.5
    宽度=math.floor(宽度)
    UILabel(页数,变量名,16,"left",'180,180,180',math.floor(w/3.8),1) UIEdit(页数,变量名,"",默认值 or '',15,"left","255,0,0","default",宽度)
end
function UI.单选框(变量名,列表,默认序号,宽度,页数)
    页数=页数 or 1
    默认序号=默认序号 or '0' 宽度=math.floor(宽度 or w/10*7)
    UILabel(页数,变量名,16,"left",'180,180,180',math.floor(w/3.8),1) UIRadio(页数,变量名,列表,默认序号,宽度)
end
function UI.开关(变量名,默认序号,页数)
    页数=页数 or 1
    if not 默认序号 then 默认序号=''
    elseif 默认序号=='0' then 默认序号=''
    elseif 默认序号=='1' then 默认序号='0'
    end
    UICheck({id=变量名,list=变量名,select=默认序号,num=页数,size=50})
end
function UI.下拉框( 变量名,列表,默认序号,宽度,页数)
    页数=页数 or 1
    默认序号=默认序号 or '0' 宽度=math.floor(宽度 or w*0.5)
    UILabel(页数,变量名,16,"left",'180,180,180',math.floor(w/3.8),1) UICombo(页数,变量名,列表,默认序号,宽度)
end
function UI.多选框( 变量名,默认序号,宽度,页数)
    默认序号=默认序号 or ''
    宽度=math.floor(宽度 or w*0.95)
    页数=页数 or 1
    UICheck({num=页数,id=变量名,list=变量名,width=宽度,select=默认序号,sel=默认序号})
end
function UI.显示()
    UIShow()
end
--------
function 浮窗(str)
	local sfbl=getScreenSize()/750
    fwShowWnd("window1",70*sfbl,40*sfbl,660*sfbl,400*sfbl,1);
    fwShowTextView("window1","text1",str,"center","FF0000","FFDAB9",20,0,30*sfbl,30*sfbl,600*sfbl,200*sfbl,{alpha = 0.5,radius = 10*sfbl});
    fwShowButton("window1","button1","完成","FFFFFF","0xfe6840","",15,450*sfbl,220*sfbl,600*sfbl,280*sfbl);
    while (true) do local vid,kind = fwGetPressedButton(); if vid == "button1" then break end end
    fwCloseWnd("window1");
    toast('脚本继续',1) mSleep(100)
end
function 浮标(x,y,t)
    fwShowWnd("toast_",x-10,y-20,x+10,y,0)
    fwShowTextView('toast_','提示','↓',"center","","FFFFFF",0,0,0,20,20,0.5)
    mSleep(1000*(t or 1))
    fwCloseView('toast_','提示');
    fwCloseWnd('toast_')
end
function 浮标s(x,y,t)
    function c浮标(x,y,t)
        local title = os.time()
        fwShowWnd(title,x-10,y-20,x+10,y,0)
        fwShowTextView(title,'提示','↓',"center","","FFFFFF",0,0,0,20,20,0.5)
        mSleep(1000*(t or 1))
        fwCloseView(title,'提示');
        fwCloseWnd(title)
    end
    thread.create(function() c浮标(x,y,t) end)
end
--------

--------
function d(tab,x,y)
    if not tab then return d(1) end
    if type(tab)=='number' then return mSleep(tab*1000) end
	if type(tab)=='string' then p('↓'..tab..' x='..x..' y='..y) tap(x,y) d() return end
    if not tab.out and tab[1] then tab.out=tab[1][1] end
    if not tab.out and tab.scr then tab.out=tab.scr[1] end
    if not tab.name and tab[1] then tab.name=tab[1][1] end
    if not tab.name and tab.scr then tab.name=tab.scr[1] end
    tab.fun=tab.fun or {}
    tab.scr=tab.scr or {}
    tab.time=tab.time or 10
    tab.s=tab.s or 1
    local js=1
	local p_str='○'
    p_(p_str..tab.name)
    while 1 do
        local str,str_,scr
        keepScreen(true)
        for i=1,#tab do
            if tab[i] then str=tab[i] else break end
            for i=3,#str do if not isColor(str[i][1],str[i][2],str[i][3]) then str=nil break end end
            if str then x,y=str[2][1],str[2][2] str=str[1] end
            if str and tab.fun[str] then p('√'..str) if tab.fun[str](str,x,y) then return true end end
            if str and not tab.fun[str] then d(str,x,y) end
            if str then break end
        end
        keepScreen(false)
        for i=1,#tab.scr do
            if str then break end
            str=tab.scr[i]:split('-')[1]
            str_=tab.scr[i]:split('-')[2]
            scr=scr or getscr() or ''
            _,x,y=scr2xy(str,scr)
            if x then x=x+6 y=y+3 else str=nil end
            if str and str_ and not scr2xy(str_,scr) then str=nil end--不满足第2个条件
            if str and tab.fun[str] then p('√'..str) if tab.fun[str](str,x,y) then return true end end
            if str and not tab.fun[str] then d(str,x,y) end
            if str then break end
        end
        if str then js=1 p_str='○' else p_str=p_str..'>' p_(p_str) end
        if str==tab.out then return str,x,y end
        if not str then js=js+tab.s end
        if not str and js>tab.time then p('✘'..tab.name) return end
        if not str then mSleep(tab.s*1000) end
    end
end
---------------------colud
xxt_cloud=function(Server_Ip,Http_Prot,aes_key)
    local cloud_cc = {}
    local Http_TimeOut = 20
    local post = function(api,head,messages,data);
        local code, header, body = http.post(
            string.format('http://%s:%s/%s',Server_Ip,Http_Prot,api),
            Http_TimeOut,
            {
                ["device_sns"] = sz.system.serialnumber(),
                ["device_head"] = (head or "0"):base64_encode(),
                ["device_messages"] = (messages or "0"):base64_encode(),
                ["device_aes"] = (tostring(getRndNum())..","..sz.system.serialnumber()..","..tostring(os.time())):aes128_encrypt(aes_key):base64_encode()
                },
            data
            )
            return code,body
    end
    cloud_cc.file = {
        take_line = function(path,line);--获取服务端文件一行数据并删除.
            return post("CCC_Device_File_TakeLine",path,tostring(line) or "1")
        end,
        get_line = function(path,line);--获取服务端文件一行数据.
            return post("CCC_Device_File_GetLine",path,tostring(line) or "1")
        end,
        insert_line = function(path,line,data);--向服务端文件插入一行数据.
            return post("CCC_Device_File_InsertLine",path,tostring(line) or "-1",data)
        end,
        set_line = function(path,line,data);--设置服务端文件指定行内容.
            return post("CCC_Device_File_SetLine",path,tostring(line) or "1",data)
        end,
        remove_line = function(path,line);--删除服务端文件指定行.
            return post("CCC_Device_File_RemoveLine",path,tostring(line) or "-1")
        end,
        list = function(path);--获取服务端文件列表.
            return post("CCC_Device_File_List",path)
        end,
        info = function(path);--获取服务端文件信息.
            return post("CCC_Device_File_Info",path)
        end,
        reads = function(path);--读取服务端文件
            return post("CCC_Device_File_Reads",path)
        end,
        writes = function(path,data);--将数据覆盖写入到服务端文件.
            return post("CCC_Device_File_Writes",path,"",data)
        end,
        remove = function(path);--删除服务端文件
            return post("CCC_Device_File_Remove",path)
        end
        };
    return cloud_cc
end
-- cloud=xxt_cloud('114.132.233.206',3825,'???')
------------------------------------

--------
-- temp=readFileString('/var/mobile/Media/TouchSprite/config/run.cfg'):split('.')

-- if temp[2]=='tsp' then
	
-- 	temp=temp[1]:split('/') code,_,body=http.get('https://????-1301815592.cos.ap-guangzhou.myqcloud.com/'..temp[#temp]..'.lua')
	
-- 	if code==200 then loadstring(body:split('华丽分割线')[1])() else dialog("脚本数据下载失败\n错误码："..temp[#temp]..'\n反馈qq：???', 0) end

-- end
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------
----------------------------------------------------------------

--]==]